<!--
 * @Author: Wangtao
 * @Date: 2020-10-22 19:27:39
 * @LastEditors: zhanwang
 * @LastEditTime: 2021-11-19 16:22:57
-->
<template>
  <continer>
    <template slot="content">
      <el-form
        class="m7-form"
        :label-position="labelPosition"
        :rules="rules"
        :model="formData"
        size="mini"
        ref="nodeForm"
      >
        <el-form-item label="节点名称" prop="name">
          <el-input v-model="formData.name" size="mini" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item label="分支" prop="name">
          <span slot="label">
                分支
                <el-tooltip class="item" effect="dark" content="分支可以拖动排序，路由判断按照分值从上到下的顺序执行，如有重复则执行较前的分值分配。" placement="top">
                  <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
                </el-tooltip>
               <span style="float: right">{{formData.routes ? formData.routes.length : 0}}/10</span>
          </span>
          <draggable  v-model="formData.routes">
          <div v-for="(item, index) in formData.routes" :key="index + 'model'">
            <model :ref='index + "model"' :data="item" :cascaderList='cascaderList' :condition='condition[index+1]' @delBranch='delBranch' :id='index' :nodeList="nodeList" :currentData='currentData' />
          </div>
          </draggable>
        </el-form-item>
        <span @click="addBranch" style="cursor:pointer"><i class="V7_iconfont V7_iconV7tubiao_xinzeng add-span"></i>添加分支</span>

        <el-form-item  style="margin-top: 20px" label="其他">
         <el-select
            v-if="condition[0]"
            v-model="condition[0].to"
            placeholder="请选择下一步节点"
            clearable
            filterable
            style="width: 100%; margin-top: 10px"
          >
            <el-option
              v-for="(node, index) in nodeList"
              :label="node.data.name"
              :value="node.id"
              v-show="!node.viewOnly && node.id !== currentData.id"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template slot="oprate">
      <el-button @click="cancel" size="mini">取消</el-button>
      <el-button type="primary" @click="onSave" size="mini">确定</el-button>
    </template>
    <template slot="remove">
      <el-button @click="deleteNode" type='danger' size="mini">删除</el-button>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Mixins } from 'vue-property-decorator'
import continer from '@/components/configCommon/ui-modules/drawer-container.vue'
import nodeEidtMixins from './nodeEidtMixins'
import { deepClone, commonAction } from '@/utils/common'
import model from './model/model.vue'
import draggable from 'vuedraggable'
// import remoteSelect from '@/components/configCommon/operate-modules/remoteSearch/index.vue'
@Component({
  name: 'ivr-node-dynamic-route',
  components: { continer, model, draggable }
})
export default class extends Mixins(nodeEidtMixins) {
  // public $message
  get cascaderList () { // 参数级联数据
    const list = [
      {
        key: 'fixed',
        memo: '系统参数',
        children: this.publicList
      },
      {
        key: 'custom',
        memo: '自定义参数',
        children: this.customParametersList
      }
    ]
    return list
  }

  private publicList: any = []
  private getPublicCustom () {
    const url = '/base/action/general/cache/query'
    commonAction({ url, method: 'post', data: { types: ['ivrSystemVariableList'] } }).then(res => {
      if (res.success) {
        this.publicList = res.ivrSystemVariableList || []
      }
    })
  }

  get customParametersList () {
    const arr = deepClone(this.data.nodeList)
    const list = arr.find(item => item.id === 'startNode').data?.customList?.filter(i => i.key) || []
    for (let i = 0; i < list.length; i++) {
      const element = list[i]
      element.memo = `${element.key} ${element.memo}`
    }
    return list
  }

  private created () {
    this.getPublicCustom()
    // if (!this.formData.routes) {
    //   this.formData.routes = [{ name: '分支1', operator: 'and', next: '', conditions: [{ k: '', op: '', v: '' }],
    //           conditon: { label: `分支1`, to: '', value: '' }
    //   }]
    // }
    // this.formData.routes.forEach((e, i) => {
    //   if (!e.conditon) {
    //     e.conditon = { label: `分支${i + 1}`, to: '', value: '' }
    //   }
    // });
    // this.$set(this.formData, 'routes', [{name: '分支1', operator: 'and', next: '', conditions: [{k: '', op: '', v: ''}]}])
  }

  private addBranch () {
    if (this.formData.routes.length >= 10) {
      this.$message('分支不能超过10个')
      return
    }
    this.condition.push({ label: `分支${this.formData.routes.length + 1}`, to: '', value: '' })
    this.formData.routes.push({
      name: `分支${this.formData.routes.length + 1}`,
      operator: 'and',
      next: '',
      conditions: [{ k: '', op: '', v: '' }],
      conditon: { label: `分支${this.formData.routes.length + 1}`, to: '', value: '' }
    })
    // this.$forceUpdate()
  }

  private delBranch (index) {
    if (this.formData.routes && this.formData.routes.length <= 1) {
      this.$message('分支不能少于1个')
      return
    }
    this.formData.routes.splice(index, 1)
    // this.condition.splice(index + 1, 1)
  }

  private onSave () {
    let num = 0
    for (let i = 0; i < this.formData.routes.length; i++) {
      const item: any = this.$refs[i + 'model'][0]
      item.showData()
      item.$refs.Form.validate(valid => {
        if (valid) {
          num++
        }
      })
    }
    this.condition.splice(1)
    this.formData.routes.forEach((e, index) => {
      this.condition[index + 1] = e.condition
      delete e.condition
      delete e.valueList
      e.conditions.forEach(q => {
        if (!Array.isArray(q.v)) {
          q.v = [q.v]
        }
      })
    });
    if (num === this.formData.routes.length) {
      this.onSubmit()
    }
    //
  }
}
</script>

<style lang="stylus" scoped>
  .audioProgress
    margin 0 10px 0
  .tip-span
    color $icon-gray
    cursor pointer
    margin-left 4px
    font-size 14px
.add-span
  font-size 12px
  cursor pointer
  &:before
    margin-right 4px
</style>
